<template>
  <el-form
      label-width="80px"
      style="max-width: 95%;">

    <el-form-item label="老师姓名">
      <el-input v-model="teacherQuery.name" @blur="checkName"/>
      <span style="color: red;"> {{formError.nameMsg}} </span>
    </el-form-item>


    <el-form-item label="老师年龄">
      <el-input v-model="teacherQuery.age" @blur="checkAge"/>
      <span style="color: red;"> {{formError.ageMsg}} </span>
    </el-form-item>

    <el-form-item label="老师研究方向">
      <el-input v-model="teacherQuery.profession" @blur="checkProfession"/>
      <span style="color: red;"> {{formError.professionMsg}} </span>
    </el-form-item>

    <el-form-item>
      <el-input type="hidden" v-model="teacherQuery.id"/>
      <el-button type="primary" @click="addTeacherSubmit">提 交</el-button>
      <el-button type="success" plain @click="back">返 回</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {doGet, doPost, doPut} from "@/http/axios-http";
import {message} from "@/http/message";

export default {

  data() {
    return {
      //老师对象，初始值是空
      teacherQuery : {},
      //form表单错误对象，初始值是空
      formError : {},
    }
  },

  mounted() {
    //根据路由id加载市场老师数据
    this.loadActivity();
  },

  methods : {
    //返回
    back() {
      //回退到上一次访问的页面
      //this.$router.go(-1);
      //精确地回到某个页面
      this.$router.push({path : "/teacherDash/teacher_info"})
    },

    //录入市场老师（提交保存）
    addTeacherSubmit() {
      //表单提交，使用formData提交表单
      let formData = new FormData();
      for (let field in this.teacherQuery) {
        formData.append(field, this.teacherQuery[field]);
      }

      if (this.teacherQuery.id) { //this.teacherQuery对象有id，说明的做了一次查询，那么就修改
        doPost("/teacher/tea_info/edit", formData).then(resp => {
          if (resp.data.code === 200) {
            //提示一下
            message("编辑老师信息成功", "success");
            //跳转到老师列表页
            this.$router.push({path : "/teacherDash/teacher_info"})
          } else {
            //提示一下
            message("编辑老师信息失败，原因：" + resp.data.msg, "error");
          }
        })
      } else {
        doPost("/teacher/tea_info/edit", formData).then(resp => {
          console.log(resp)
          if (resp.data.code === 200) {
            //提示一下
            message("录入老师信息成功", "success");
            //跳转到老师列表页
            this.$router.push({path : "/teacherDash/teacher_info"})
          } else {
            //提示一下
            message("录入老师信息失败，原因：" + resp.data.msg, "error");
          }
        })
      }
    },

    //根据路由id加载市场老师数据
    loadActivity() {
      let id = this.$route.params.id;
      if (id) {
        //编辑需要把数据查出来
        doGet("/teacher/tea_info/getById/" + id, {}).then(resp => {
          this.teacherQuery = resp.data.data;
        })
      }
    }
  }
}
</script>